<!-- 新增轮播 -->
<template>
  <div class="addCarousel">
    <div class="pageHeader">
      <i class="el-icon-arrow-left" @click="goBack"></i>
      <span v-if="num == 1">新增轮播</span>
      <span v-else-if="num == 2">编辑轮播</span>
      <span v-else>轮播详情</span>
    </div>

    <div class="carouselBox">
      <myForm :formConfig="formConfig" :formData="form" :labelWidth="labelWidth" :formInline="formInline" ref="addForm">
        <!-- 轮播图 -->
        <template slot="image">
          <el-upload class="avatar-uploader" accept="image/*" :show-file-list="false" :http-request="httpRequest"
            v-if="num != 3" action="" :before-upload="beforeUpload" v-loading="loading1">
            <!-- 图片容器（用于定位删除按钮） -->
            <div class="avatar-wrapper" v-if="form.image">
              <img :src="form.image" class="avatar" />
              <!-- 删除按钮 -->
              <el-button class="delete-btn" icon="el-icon-delete" circle size="mini" v-if="num != 3"
                @click.stop="handleDelete"></el-button>
            </div>
            <!-- 无图片时的默认图标 -->
            <i class="el-icon-plus avatar-uploader-icon" v-else></i>
          </el-upload>
          <img :src="form.image" class="avatar" v-else style="border:1px dashed #d9d9d9;" />
        </template>

        <!-- 状态 -->
        <template slot="status">
          <el-switch v-model="form.status" :active-value="activeStatus" :inactive-value="inactiveStatus"
            :disabled="num == 3"></el-switch>
        </template>
      </myForm>

      <div v-if="num != 3">
        <el-button type="primary" @click="add" :loading="loading">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { businessId } from "@/api/pFile";
import { uploadFile, delFile, downFile } from "@/api/common";
import { addBanner, queryById, updateBanner } from "@/api/carouselManagement";
export default {
  name: "addCarousel",
  components: {},
  data() {
    return {
      formInline: false,
      labelWidth: "100px",
      form: {},
      formConfig: [
        {
          label: "轮播名称",
          prop: "name",
          type: "input",
          placeholder: "请输入轮播名称",
          rules: [
            { required: true, message: "请输入轮播名称", trigger: "blur" }
          ],
          disabled: false
        },
        {
          label: "轮播图",
          slotName: "image",
          prop: "image",
          rules: [
            { required: true, message: "请上传轮播图", trigger: "change" }
          ],
          disabled: false
        },
        {
          label: "轮播内容",
          prop: "content",
          type: "textarea",
          rules: [
            { required: true, message: "请输入轮播内容", trigger: "blur" }
          ],
          disabled: false
        },
        {
          label: "是否启用",
          slotName: "status",
          prop: "status",
          rules: [{ required: true, message: "请选择状态", trigger: "change" }],
          disabled: false
        }
      ],
      activeStatus: 1,
      inactiveStatus: 0,
      bussinessId: "",
      loading: false,
      loading1: false,
      file: '',
      id: this.$route.query.id,
      num: this.$route.query.num
    };
  },
  created() {
    this.getBusinessId();
    this.formConfig.forEach((item => {
      if (this.num == 3) {
        item.disabled = true;
      } else {
        item.disabled = false;
      }
    }))
    if (this.num != 1) {
      this.queryById();
    }
  },
  methods: {
    queryById() {
      queryById({ bannerId: this.id }).then((res) => {
        this.form = res.data;
      })
    },
    downFile(row) {
      downFile({ fileId: row.id }).then((res) => {
        this.$set(row, 'url', window.URL.createObjectURL(new Blob([res.data])));
      })
    },
    getBusinessId() {
      businessId().then(res => {
        this.bussinessId = res.data;
      });
    },
    // 返回
    goBack() {
      this.$router.push("/carouselManagement");
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith("image/");
      if (!isImage) {
        this.$message.error("只能上传图片文件！");
        return false;
      }
      const size = file.size / 1024 / 1024;
      const isFileSize = size > 5; //最大5M
      if (isFileSize) {
        this.isFileSize = false;
        this.$message.error("上传的文件不能超过5M!");
        return false;
      }
    },
    httpRequest(item) {
      let that = this;
      const formData = new FormData();
      formData.append("bussinessId", that.bussinessId);
      formData.append("moduleId", "taskManager");
      formData.append("files", item.file);
      that.loading1 = true;
      uploadFile(formData).then((res) => {
        that.form.image = res.data[0];
        that.loading1 = false;
      }).catch((res) => {
        this.loading1 = false;
      })
    },
    // 移除文件
    handleDelete() {
      delFile({ fileId: this.form.image }).then((res) => {
        this.form.image = '';
        this.toast("删除成功", "success");
      })
    },
    add() {
      if (this.$refs.addForm.submitValidate()) {
        let post = this.num == 1 ? addBanner(this.form) : updateBanner(this.form);
        post.then((res) => {
          this.loading = false;
          this.toast("操作成功", "success");
          this.goBack();
        }).catch(() => {
          this.loading = false;
        })
      }
    }
  }
};
</script>

<style scoped lang="scss">
.addCarousel {
  padding: 0 68px;
  padding-bottom: 88px;
  background: #fff;
  border-radius: 4px;
  overflow-y: auto;
  /* 垂直方向溢出时显示滚动条 */
  height: 100vh;

  .pageHeader {
    font-size: 18px;
    font-weight: 550;
    margin-bottom: 10px;

    i {
      margin-right: 10px;
      cursor: pointer;
    }
  }

  .carouselBox {
    width: 800px;

    ::v-deep .el-input__inner {
      width: 150px;
    }

    ::v-deep .el-textarea__inner {
      height: 200px;
    }
  }

  .avatar {
    width: 148px !important;
    height: 148px !important;
  }


  ::v-deep .avatar-uploader {
    width: 148px !important;
    height: 148px !important;
  }

  ::v-deep .avatar-uploader-icon {
    width: 148px !important;
    height: 148px !important;
    line-height: 148px !important;
  }

  ::v-deep .el-upload-list__item {
    padding-right: 0;
  }

  ::v-deep .el-upload {
    height: 148px;
  }
}

.merchant-form::-webkit-scrollbar {
  display: none;
  /* 隐藏滚动条 */
}


.avatar-wrapper {
  position: relative;
  /* 作为删除按钮的定位容器 */
  display: inline-block;
}

.avatar {
  width: 100px;
  /* 图片宽度，可根据需求调整 */
  height: 100px;
  /* 图片高度，可根据需求调整 */
  border-radius: 4px;
  /* 可选：图片圆角 */
}

.delete-btn {
  position: absolute;
  top: -10px;
  /* 向上偏移，调整位置 */
  right: -10px;
  /* 向右偏移，调整位置 */
  background-color: white;
  border: 1px solid #ddd;
  box-shadow: 0 0 2px rgba(0, 0, 0, 0.2);
}
</style>